import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    Alert,
    FlatList,
    TextInput,
    Linking,
    ScrollView,
    Switch,
    DeviceEventEmitter,
} from 'react-native';
import Header from "../../../components/header";
import HttpUtils from '../../../utils/HttpUtils';
import HttpUrls from '../../../utils/HttpUrls';
import { ToastToUser } from '../../../utils/CustomToast';

let navigation

let mark = '_.'

export default class CarConfigurationPage extends Component {

    constructor(props) {
        super(props);
        let preSelectedString = this.props.route && this.props.route.params && this.props.route.params.preSelectedString ? this.props.route.params.preSelectedString : ''
        this.state = {
            preSelectedString: preSelectedString,
            preMoreInfo: '',
            selectDataSource: [],
            dataSource: [],
            showAddPop: false,
            addConfiguration: ''
        }
    }

    componentDidMount() {
        this.updatePreSelected()
        this.getConfiguration()
    }

    updatePreSelected() {
        if (this.state.preSelectedString.indexOf(mark) > 0) {
            let array = this.state.preSelectedString.split(mark)
            let selectStr = array[0]
            let selectDataSource = selectStr.split(',')
            this.setState({
                selectDataSource: selectDataSource
            })
            if (array.length >= 2) {
                this.setState({
                    preMoreInfo: array[1]
                })
            }
        } else if (this.state.preSelectedString.indexOf(mark) == 0) {
            let preMoreInfo = this.state.preSelectedString.substring(2, this.state.preSelectedString.length-1);
            this.setState({
                preMoreInfo
            })
        }
    }

    getConfiguration() {
        HttpUtils.getRequest(HttpUrls.getCarFeaturesList, {})
            .then((result) => {
                let dataSource = []
                result.data.map((title) => {
                    let item = {
                        title: title,
                        select: false,
                        type: 1,
                    }
                    this.state.selectDataSource.map((selectItemTitle) => {
                        if (title == selectItemTitle) {
                            item.select = true
                        }
                    })
                    dataSource.push(item)
                })

                this.state.selectDataSource.map((selectItemTitle) => {
                    let has = false
                    dataSource.map((item) => {
                        if (item.title == selectItemTitle) {
                            has = true
                        }
                    })
                    if (!has) {
                        let item = {
                            title: selectItemTitle,
                            select: true,
                            type: 2,
                        }
                        dataSource.push(item)
                    }
                })

                let addItem = {
                    title: '＋ 添加亮点',
                    type: 3
                }

                dataSource.push(addItem)

                this.setState({
                    dataSource: dataSource
                })
            })
            .catch((error) => {

            });
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'车辆配置'} ></Header>
                <ScrollView style={{ flex: 1 }}>
                    <View style={styles.configurationTopBox}>
                        <Text style={styles.titleText}>亮点配置</Text>
                    </View>
                    <View style={styles.configurationBg}>
                        {
                            this.state.dataSource && this.state.dataSource.map((item, index) => {
                                return (
                                    <TouchableOpacity
                                        style={[styles.itemBox, { backgroundColor: item.type == 3 ? '#fff' : item.select ? '#fedd35' : '#f5f5f5', borderWidth: item.type == 3 ? 1 : 0 }]}
                                        onPress={() => {
                                            if (item.type == 3) {
                                                this.setState({
                                                    showAddPop: true
                                                })
                                            } else {
                                                let dataSource = this.state.dataSource
                                                dataSource[index].select = !dataSource[index].select
                                                this.setState({
                                                    dataSource
                                                })
                                            }
                                        }}
                                    >
                                        <Text style={[styles.itemText, { color: item.type == 3 ? '#f99802' : '#222' }]}>{item.title}</Text>
                                        {
                                            item.type == 2 ?
                                                <TouchableOpacity
                                                    style={styles.closeBox}
                                                    onPress={() => {
                                                        let dataSource = this.state.dataSource
                                                        dataSource.splice(index, 1)
                                                        this.setState({
                                                            dataSource
                                                        })
                                                    }}
                                                >
                                                    <Text style={styles.closeText}>×</Text>
                                                </TouchableOpacity>
                                                :
                                                null
                                        }
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </View>
                    <View style={styles.supplyBox}>
                        <TextInput
                            autoCorrect={false}
                            editable={true}
                            returnKeyType='done'
                            autoCapitalize='characters'
                            style={styles.textInput1}
                            multiline={true}
                            placeholder={'补充描述越多，卖车越容易'}
                            placeholderTextColor="#999999"
                            value={this.state.preMoreInfo}
                            maxLength={500}
                            onChangeText={this.changeText.bind(this, 'preMoreInfo')}
                        />
                        <Text style={styles.conentLengthText}>{this.state.preMoreInfo.length + '/' + '500'}</Text>
                    </View>
                    <View style={{ width: '100%', paddingHorizontal: 15 }}>
                        <TouchableOpacity
                            style={styles.saveBox}
                            onPress={()=>{
                                this.save()
                            }}
                        >
                            <Text style={styles.saveText}>保存</Text>
                        </TouchableOpacity>
                    </View>
                </ScrollView>

                {
                    this.state.showAddPop ?
                        this.renderAddPop()
                        :
                        null
                }

            </View>
        )
    }

    renderAddPop() {
        return (
            <View style={styles.addBg}>
                <View style={styles.addBox}>
                    <Text style={styles.addTitleText}>添加亮点</Text>
                    <TextInput
                        autoCorrect={false}
                        editable={true}
                        returnKeyType='done'
                        autoCapitalize='characters'
                        style={styles.textInput}
                        placeholder={'请输入亮点内容'}
                        placeholderTextColor="#999999"
                        value={this.state.addConfiguration}
                        onChangeText={this.changeText.bind(this, 'addConfiguration')}
                    />
                    <TouchableOpacity
                        style={styles.sureBox}
                        onPress={() => {
                            this.addNewConfiguration()
                        }}
                    >
                        <Text style={styles.sureText}>确定</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={styles.cancelBox}
                        onPress={() => {
                            this.setState({
                                showAddPop: false
                            })
                        }}
                    >
                        <Text style={styles.cancelText}>取消</Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

    //输入框内容输入
    changeText(type, val) {
        this.setState({
            [type]: val
        })
    }

    addNewConfiguration() {
        let item = {
            title: this.state.addConfiguration,
            select: true,
            type: 2,
        }
        let dataSource = this.state.dataSource
        dataSource.splice(this.state.dataSource.length - 1, 0, item)
        this.setState({
            dataSource,
            showAddPop: false,
            addConfiguration: ''
        })
    }

    save() {
        let marray = []
        this.state.dataSource.map((item)=>{
            if (item.select) {
                marray.push(item.title)
            }
        })
        let feature = marray.join(',')
        if (!(feature.length || this.state.preMoreInfo.length)) {
            ToastToUser('您尚未设置车辆配置内容')
            return
        }
        if (feature) {
            feature = feature+mark
        } else {
            feature = mark
        }

        if (this.state.preMoreInfo) {
            feature = feature+this.state.preMoreInfo
        }

        if (this.props.route.params.editCompletion) {
            this.props.route.params.editCompletion(feature)
        }
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    configurationTopBox: {
        marginTop: 10,
        width: '100%',
        height: 44,
        paddingHorizontal: 15,
        borderBottomColor: '#e4e4e4',
        borderBottomWidth: 0.3,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
        backgroundColor: '#fff'
    },
    titleText: {
        color: '#333',
        fontSize: 14,
        fontWeight: '500'
    },
    configurationBg: {
        width: '100%',
        paddingHorizontal: 15,
        paddingBottom: 15,
        flexWrap: 'wrap',
        backgroundColor: '#fff',
        flexDirection: 'row',
    },
    itemBox: {
        marginTop: 15,
        marginRight: 12,
        paddingHorizontal: 10,
        paddingVertical: 6,
        borderRadius: 2,
        backgroundColor: '#f5f5f5',
        borderColor: '#f99802'
    },
    itemText: {
        color: '#222',
        fontSize: 12,
    },
    closeBox: {
        position: 'absolute',
        top: -5,
        right: -5,
        backgroundColor: '#fb3d3c',
        width: 15,
        height: 15,
        borderRadius: 8,
        justifyContent: 'center',
        alignItems: 'center'
    },
    closeText: {
        color: '#fff',
        fontSize: 15,
        marginTop: -2,
    },


    addBg: {
        position: 'absolute',
        width: '100%',
        height: '100%',
        zIndex: 1000,
        backgroundColor: 'rgba(0,0,0,0.6)',
        justifyContent: 'center',
        alignItems: 'center'
    },
    addBox: {
        width: '80%',
        paddingTop: 30,
        paddingBottom: 10,
        borderRadius: 10,
        backgroundColor: '#fff',
        flexDirection: 'column',
        alignItems: 'center',
        paddingHorizontal: 15,
        justifyContent: 'flex-start'
    },
    addTitleText: {
        color: '#222',
        fontSize: 16
    },
    textInput: {
        marginTop: 25,
        color: '#333333',
        fontSize: 14,
        width: '100%',
        height: 40,
        borderRadius: 6,
        paddingLeft: 10,
        borderColor: '#e4e4e4',
        borderWidth: 1
    },
    textInput1: {
        color: '#333333',
        fontSize: 14,
        width: '100%',
        height: 110,
    },
    conentLengthText: {
        position: 'absolute',
        bottom: 8,
        right: 8,
        fontSize: 13,
        color: '#888'
    },
    sureBox: {
        marginTop: 25,
        backgroundColor: '#ffde00',
        width: '100%',
        height: 40,
        borderRadius: 6,
        justifyContent: 'center',
        alignItems: 'center'
    },
    sureText: {
        fontSize: 15,
        color: '#333'
    },
    cancelBox: {
        marginTop: 15,
        width: '100%',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center'
    },
    cancelText: {
        fontSize: 15,
        color: '#999'
    },
    supplyBox: {
        marginTop: 10,
        backgroundColor: '#fff',
        paddingHorizontal: 15,
        paddingTop: 10,
        paddingBottom: 24,
        width: '100%'
    },
    saveBox: {
        marginTop: 30,
        width: '100%',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 6,
        backgroundColor: '#fedd35'
    },
    saveText: {
        fontSize: 15,
        color: '#333'
    }

})